<template>
  <div v-loading="loading">
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="coalType">
        <el-select
          multiple
          clearable
          v-model="queryParams.coalType"
          placeholder="请选择"
          class="!w-300px"
        >
          <el-option
            v-for="dict in coalTypeList"
            :key="dict.id"
            :label="dict.coalName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button-group class="ml-4">
          <el-button
            v-for="item in dateTypeList"
            :type="queryParams.timePeriod === item.value ? 'primary' : 'default'"
            @click="dateTypeChange(item.value)"
            :key="item.value"
            >{{ item.label }}</el-button
          >
        </el-button-group>
      </el-form-item>
      <el-form-item label="选择时间" prop="localDates">
        <DatePicker
          v-model="queryParams.localDates"
          :isNow="false"
          :dateType="queryParams.timePeriod"
          @dataChange="datePickerChange"
        ></DatePicker>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-card class="mt-20px">
      <el-container class="space-x-12">
        <div class="h-270px w-1/3">
          <Echart
            :height="270"
            :options="funnelOptionData"
            @clickReady="chartClick"
            @initReady="initFunnel"
          />
        </div>
        <div class="h-270px w-2/3">
          <el-table
            :data="rateList"
            border
            stripe
            class="mt-50px funnel-table"
            :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
          >
            <el-table-column label="" align="center" width="80" fixed="left">
              <template #default="{ $index }">
                <div
                  :class="{
                    'bg-0ea5e9': $index === 0,
                    'bg-f59e0b': $index === 1,
                    'bg-ec4899': $index === 2,
                    'bg-8b5cf6': $index === 3
                  }"
                  class="h-10px my-7px"
                >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="名称"
              align="center"
              prop="name"
              min-width="100"
              fixed="left"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="人数" align="center" prop="peopleNumber" min-width="100" />
            <el-table-column label="转化率" align="center" prop="conversionRate" min-width="100">
              <template #default="{ row }">
                <el-progress
                  :text-inside="true"
                  :stroke-width="16"
                  :percentage="row.conversionRate"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="月环比增速"
              align="center"
              prop="monthGrowthRate"
              min-width="100"
            >
              <template #default="{ row }">
                <span
                  v-if="isEmpty(row.monthGrowthRate)"
                  :class="{
                    'text-teal-500': row.monthGrowthRate < 0,
                    'text-red-500': row.monthGrowthRate > 0
                  }"
                  >{{ row.monthGrowthRate.toFixed(2) }}%</span
                >
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-container>
    </el-card>
    <el-card class="mt-20px">
      <el-table
        :data="list"
        border
        stripe
        :height="305"
        :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
      >
        <el-table-column label="序号" align="center" width="60" fixed="left">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          label="客户名称"
          align="center"
          prop="customerName"
          min-width="200"
          fixed="left"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="销量合计(万吨)"
          align="center"
          prop="purchaseTotal"
          min-width="150"
        />
        <el-table-column
          label="销售金额合计(万元)"
          align="center"
          prop="purchaseAmountTotal"
          min-width="150"
        />
        <el-table-column label="通知次数" align="center" prop="informNumber" min-width="100" />
        <el-table-column
          v-if="false"
          label="查看次数"
          align="center"
          prop="viewNumber"
          min-width="100"
        />
        <el-table-column label="报名次数" align="center" prop="signUpNumber" min-width="100" />
        <el-table-column label="竞价人数" align="center" prop="bidPriceNumber" min-width="100" />
        <el-table-column label="中标人数" align="center" prop="bidNumber" min-width="100" />
        <el-table-column
          label="平均价格(元/吨)"
          align="center"
          prop="averagePrice"
          min-width="140"
        />
        <el-table-column
          label="平均起拍价(元/吨)"
          align="center"
          prop="averageStartPrice"
          min-width="150"
        />
        <el-table-column
          label="平均溢价(元/吨)"
          align="center"
          prop="averagePremium"
          min-width="140"
        />
        <el-table-column
          label="最高中标价格(元/吨)"
          align="center"
          prop="highestBidPrice"
          min-width="160"
        />
        <el-table-column
          label="最低中标价格(元/吨)"
          align="center"
          prop="lowestBidPrice"
          min-width="160"
        />
        <el-table-column
          label="保证金合计(万元)"
          align="center"
          prop="marginTotal"
          min-width="150"
        />
        <el-table-column
          label="保证金扣款合计(万元)"
          align="center"
          prop="marginDeductionTotal"
          min-width="170"
        />
        <el-table-column
          label="退保证金合计(万元)"
          align="center"
          prop="returnMarginTotal"
          min-width="150"
        />
        <el-table-column
          label="充值金额(万元)"
          align="center"
          prop="rechargeAmount"
          min-width="140"
        />
        <el-table-column
          label="可用资金余额(万元)"
          align="center"
          prop="availableFunds"
          min-width="150"
        />
        <el-table-column label="保证金余额(万元)" align="center" prop="bond" min-width="150" />
      </el-table>
    </el-card>
  </div>
</template>
<script setup lang="ts" name="conversionRateAnalysis">
import * as dataCenter from '@/api/dataCenter'
import echarts from '@/plugins/echarts'
import { EChartsOption } from 'echarts'
import { funnelOption } from '../echarts-data'
import { formatDate } from '@/utils/formatTime'
import { isEmpty, initMonthTimeRange } from '@/utils/common'
import { dateTypeList } from '../dataCenter.data'
import { cloneDeep } from 'lodash-es'

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const rateList: Record<string, any> = ref([])
const queryFormRef = ref()
const funnelChart = ref()
const message = useMessage()
const coalTypeList: Record<string, any> = ref([])
const funnelOptionData = reactive<EChartsOption>(funnelOption) as EChartsOption
const queryParams: Record<string, any> = ref({
  coalType: [],
  timePeriod: 'month',
  localDates: []
})
const labelToKeyMap = {
  触达人数: 'informNumber',
  查看人数: 'viewNumber',
  报名人数: 'signUpNumber',
  竞价人数: 'bidPriceNumber',
  中标人数: 'bidNumber'
}
const dataStyleMap = {
  触达人数: {
    color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
      { offset: 0, color: '#7dd3fc' },
      { offset: 1, color: '#0ea5e9' }
    ])
  },
  查看人数: {
    color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
      { offset: 0, color: '#6ee7b7' },
      { offset: 1, color: '#10b981' }
    ])
  },
  报名人数: {
    color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
      { offset: 0, color: '#fcd34d' },
      { offset: 1, color: '#f59e0b' }
    ])
  },
  竞价人数: {
    color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
      { offset: 0, color: '#f9a8d4' },
      { offset: 1, color: '#ec4899' }
    ])
  },
  中标人数: {
    color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
      { offset: 0, color: '#ddd6fe' },
      { offset: 1, color: '#8b5cf6' }
    ])
  }
}
let cacheList = []
let timeTange: any[] = []

const getList = () => {
  loading.value = true
  try {
    getConversionStatistics()
    getCustomerStatistics()
  } finally {
    loading.value = false
  }
}

const getConversionStatistics = async () => {
  const params = cloneDeep(queryParams.value)
  if (params.coalType.length) {
    params.coalId = params.coalType.join(',')
  }
  params.localDates = timeTange
  delete params.coalType
  const res = await dataCenter.getConversionStatistics(params)
  rateList.value = (res?.conversionBaseRespVOS || []).filter((e) => e.name !== '查看人数')
  initFunnelData(res?.dataRespVOList || [])
}

const getCustomerStatistics = async () => {
  const params = cloneDeep(queryParams.value)
  if (params.coalType.length) {
    params.coalId = params.coalType.join(',')
  }
  params.localDates = timeTange
  delete params.coalType
  const res = await dataCenter.getCustomerStatistics(params)
  cacheList = res || []
  list.value = res || []
}

const handleQuery = () => {
  if (timeTange.length !== 2) {
    message.warning('选择时间不能为空')
    return
  }
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.value.timePeriod = 'month'
  timeTange = initMonthTimeRange()
  nextTick(() => {
    queryParams.value.localDates = formatDate(new Date(), 'YYYY-MM-DD')
  })
  handleQuery()
}

const dateTypeChange = (type) => {
  timeTange = []
  queryParams.value.timePeriod = type
  if (type === 'daterange') {
    queryParams.value.localDates = []
  } else {
    queryParams.value.localDates = undefined
  }
}

const datePickerChange = ($event) => {
  timeTange = $event
}

const chartClick = (data) => {
  const result = cloneDeep(cacheList || [])
  list.value = result.filter((e) => !!e[labelToKeyMap[data.name]])
}

const initFunnel = (chart) => {
  funnelChart.value = chart
}

const initFunnelData = (list) => {
  funnelChart.value.setOption({
    title: {
      text: '转化率分析'
    },
    series: [
      {
        name: '转化率分析',
        sort: 'none',
        left: '25%',
        right: '25%',
        data:
          list
            ?.filter((m) => m.dataName !== '查看人数')
            ?.map((e) => {
              return {
                max: getMaxValue(list),
                name: e.dataName,
                value: e.value + 10,
                itemStyle: dataStyleMap[e.dataName],
                label: {
                  formatter: (param) => {
                    return param.value - 10
                  }
                }
              }
            }) || []
      }
    ]
  })
}

const getMaxValue = (list) => {
  if (!list.length) {
    return 0
  }
  return Math.max(...list.map((e) => e.value))
}

const bidCoalManageList = async () => {
  const res = await dataCenter.bidCoalManageList()
  coalTypeList.value = res || []
}

onMounted(() => {
  queryParams.value.localDates = formatDate(new Date(), 'YYYY-MM-DD')
  timeTange = initMonthTimeRange()
  bidCoalManageList()
  getList()
})
</script>
<style lang="scss" scoped>
.bg-0ea5e9 {
  background-color: #0ea5e9;
}
.bg-10b981 {
  background-color: #10b981;
}
.bg-f59e0b {
  background-color: #f59e0b;
}
.bg-ec4899 {
  background-color: #ec4899;
}
.bg-8b5cf6 {
  background-color: #8b5cf6;
}
:deep(.el-progress-bar__inner) {
  text-align: left !important;
}
</style>
